package servlet;

import java.io.IOException;

import javax.servlet.ServletException;

import toolkit.Debug;
import validate.AddressValidator;
import validate.TelephoneNumberValidator;
import validate.WordsValidator;
import bean.NameBean;
import domain.entity.User;
import form.Form;
import form.element.TextInput;

public class NameServlet extends AbstractStepServlet
{
	private static final long serialVersionUID = 1L;
	
	private Form form;
	
	public NameServlet()
	{
		Debug.log("(" + id + ") NameServlet()");
	}
	
	@Override
	public void init()
			throws ServletException
	{
		super.init();
		
		form = new Form("name");
		
		TextInput name = new TextInput("name");
		name.setLabel("Naam");
		name.setRequired();
		name.addValidator(new WordsValidator());
		form.addChild(name);
		
		TextInput address = new TextInput("address");
		address.setLabel("Adres");
		address.setRequired();
		address.addValidator(new AddressValidator());
		form.addChild(address);

		TextInput city = new TextInput("city");
		city.setLabel("Plaats");
		city.setRequired();
		city.addValidator(new WordsValidator());
		form.addChild(city);

		TextInput phonenumber = new TextInput("phonenumber");
		phonenumber.setLabel("Telefoonnummer");
		phonenumber.setRequired();
		phonenumber.addValidator(new TelephoneNumberValidator());
		form.addChild(phonenumber);
	}
	
	@Override
	public void preDispatch()
	{
		super.preDispatch();
		
		form.clear();
	}
	
	@Override
	public void dispatchGet()
			throws ServletException, IOException
	{
		Debug.log("(" + id + ") NameServlet.dispatchGet()");
		
		User user = (User) session.getAttribute("user");
		
		Debug.log("user = " + user);
		
		if (user != null && method == "get")
		{
			Debug.log("values = " + pizzaManager.getEntityValues(user));
			
			form.populate(pizzaManager.getEntityValues(user));
		}
		
		display();
	}
	
	@Override
	public void dispatchPost()
			throws ServletException, IOException
	{
		Debug.log("(" + id + ") NameServlet.dispatchPost()");
		
		NameBean bean = (NameBean) getPostValuesBean();
		
		if (bean != null)
		{
			form.populate(bean);
		}
		
		if (form.isValid())
		{
			User user = (User) session.getAttribute("user");
			
			if (user == null)
			{
				user = new User();
			}
			
			pizzaManager.populateEntity(user, form.getValues());
			
			session.setAttribute("user", user);
			
			redirectNextStep();
		}
		else
		{
			dispatchGet();
		}
	}
}
